﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace HttpCrawler
{
    public static class ParallelHelper
    {
        private static IEnumerable<bool> IterateUntilFalse(Func<bool> condition)
        {
            while (condition())
            {
                yield return true;
            }
        }

        /// <summary>
        /// Parallel While pattern which prevents exiting the loop while iterations are still processing.
        /// </summary>
        public static void While(Func<bool> condition, Action body)
        {
            var sync = new Object();
            int counter = 0;
            Parallel.ForEach(ParallelHelper.IterateUntilFalse(() =>
            {
                lock (sync)
                {
                    var shouldContinue = true;

                    if (counter > 0)
                    {
                        shouldContinue = true;
                    }
                    else
                    {
                        shouldContinue = condition();
                    }

                    if (shouldContinue)
                    {
                        counter++;
                    }

                    return shouldContinue;
                }
            }), b => 
            {
                body();

                lock (sync)
                {
                    counter--;
                }
            });
        }
    }
}
